package com.zzh.webhook.service;

import com.zzh.webhook.config.ProjectConfig;
import com.zzh.webhook.utils.CommandExecutor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
@RequiredArgsConstructor
public class BuildService {
    
    private final CommandExecutor commandExecutor;
    private final ProjectConfig projectConfig;
    private final DockerService dockerService;
    private final GitService gitService;
    
    /**
     * 构建指定模块
     *
     * @param moduleName 模块名称
     * @throws IOException 如果构建过程中出现IO异常
     */
    public void buildModule(String moduleName) throws IOException {
        String localPath = projectConfig.getGit().getLocalPath();

        log.info("Building module: {}", moduleName);


        String mvnPath = "D:\\Environment\\Maven\\apache-maven-3.6.3\\bin\\mvn.cmd";

        // 执行构建前命令
        String preBuildCommand = mvnPath+ " clean package -pl " + moduleName +" -am";
        commandExecutor.execute(preBuildCommand, localPath);


        String modulePath = localPath.concat(File.separator).concat(moduleName);


        // 构建Docker镜像
        String buildCommand = "docker build -t zzh-"+ moduleName +" .";
        commandExecutor.execute(buildCommand, modulePath);
//        String imageId = dockerService.buildImage(moduleName);

        // 创建并启动Docker容器
        // 构建Docker镜像
        String startContainCommand = "docker run -d -p 4016:4016 --name zzh-"+moduleName+ " "+"zzh-"+moduleName+":latest";
        commandExecutor.execute(startContainCommand, modulePath);

//        dockerService.createAndStartContainer(moduleName, "zzh");
    }
    
    /**
     * 根据修改的文件确定需要构建的模块，并执行构建
     * 
     * @param changedFiles 修改的文件列表
     * @throws IOException 如果构建过程中出现IO异常
     */
    public void buildAffectedModules(List<String> changedFiles) throws IOException {
        // 检查是否有公共模块被修改
        boolean isCommonModuleChanged = gitService.isCommonModuleChanged(changedFiles);
        
        List<String> modulesToBuild = new ArrayList<>();
        
        if (isCommonModuleChanged) {
            // 如果公共模块被修改，构建所有模块
            log.info("Common module changed, building all modules");
            modulesToBuild.addAll(projectConfig.getModules().getAllModules());
        } else {
            // 如果只有特定模块被修改，只构建受影响的模块
            Set<String> affectedModules = gitService.getAffectedModules(changedFiles);
            log.info("Building affected modules: {}", affectedModules);
            modulesToBuild.addAll(affectedModules);
        }
        
        // 执行构建
        for (String moduleName : modulesToBuild) {
            buildModule(moduleName);
        }
    }
} 